package com.moleq.mgpos.activities;

import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.moleq.adapter.GlobalDiscountAdapter;
import com.moleq.adapter.ItemDiscountAdapter;
import com.moleq.base.EditableListener;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.mgpos.widget.BeepImageButton;
import com.moleq.mgpos.widget.ScrollLayout;
import com.moleq.mgpos.widget.ScrollLayout.OnSwichScreen;
import com.moleq.models.GlobalDiscountSetting;
import com.moleq.models.GlobalInfo;
import com.moleq.models.ItemDiscountSetting;
import com.moleq.mgpos.activities.R;
import com.moleq.service.GlobalDiscountSettingService;
import com.moleq.service.ItemDiscountSettingService;
import com.moleq.service.ServiceManager;
import com.moleq.util.ChangeMode;
import com.moleq.util.MoleQUtil;

public class DiscountSettingActivity extends Activity{
	
	private Context sharedContext = null;
	private ScrollLayout scrollLayout;
	private ItemDiscountSettingService itemDiscountService = null;
	private GlobalDiscountSettingService globalDiscountService = null;
	private List<ItemDiscountSetting> listItemDiscount = null;
	private List<GlobalDiscountSetting> listGlobalDiscount = null;
	private ItemDiscountAdapter itemDiscountAdapter;
	private GlobalDiscountAdapter globalDiscountAdapter;
	
	private int msgType = 0;
	private int msg;
	private boolean result = false;
	private LinearLayout ll_left,ll_right;
	private ListView lv_itemDiscountlist,lv_globalDiscountList;
	private Button btn_exit;
	private BeepImageButton iv_dis_add,iv_dis_delete,iv_dis_ok,iv_global_add,iv_global_delete,iv_global_ok;
	private ImageView iv_1_w1,iv_1_b2,iv_2_b1,iv_2_w2;
	private MessageDialog mMessageDialog;
	private boolean isModified = false;
	
	Date now = new Date();
	private MGCreateFiles mMGCreateFiles = new MGCreateFiles();
	
	public OnSwichScreen mOnSwichScreen = new OnSwichScreen(){

		@Override
		public void onTriggerToDo(int iScreen) {
			switch (iScreen) {
			case 0:		//DiscountSetting
				setPage(0);
				ChangeMode.mode = 1;
				itemDiscountAdapter.ScrollToRow(0);
				break;
			case 1:		//Coupon Setting
				setPage(1);
				ChangeMode.mode = 1;
				globalDiscountAdapter.ScrollToRow(0);
				break;
			}
		}
	};
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_discount_setting);
        
        ll_left = (LinearLayout) findViewById(R.id.ll_left);
        ll_right = (LinearLayout) findViewById(R.id.ll_right);
        scrollLayout = (ScrollLayout) findViewById(R.id.ScrollLayoutTest);
        scrollLayout.setOnSwichScreen(mOnSwichScreen);
        
        btn_exit = (Button) findViewById(R.id.btn_exit);
        lv_itemDiscountlist = (ListView) findViewById(R.id.lv_itemDiscountlist);
        lv_globalDiscountList = (ListView) findViewById(R.id.lv_globalDiscountList);
        iv_dis_add = (BeepImageButton) findViewById(R.id.iv_dis_add);
        iv_dis_delete = (BeepImageButton) findViewById(R.id.iv_dis_delete);
        iv_dis_ok = (BeepImageButton) findViewById(R.id.iv_dis_ok);
        iv_global_add = (BeepImageButton) findViewById(R.id.iv_global_add);
        iv_global_delete = (BeepImageButton) findViewById(R.id.iv_global_delete);
        iv_global_ok = (BeepImageButton) findViewById(R.id.iv_global_ok);
        
        iv_1_w1 = (ImageView) findViewById(R.id.iv_1_w1);
        iv_1_b2 = (ImageView) findViewById(R.id.iv_1_b2);
        iv_2_b1 = (ImageView) findViewById(R.id.iv_2_b1);
        iv_2_w2 = (ImageView) findViewById(R.id.iv_2_w2);
        
        iv_1_b2.setOnClickListener(onPageClickListener);
        iv_2_b1.setOnClickListener(onPageClickListener);
        
        lv_itemDiscountlist.setDividerHeight(0);
        lv_globalDiscountList.setDividerHeight(0);
        ll_left.setOnClickListener(onClickListener);
        ll_right.setOnClickListener(onClickListener);
        btn_exit.setOnClickListener(onClickListener);
        
        iv_dis_add.setOnClickListener(onImageClickListener);
        iv_dis_delete.setOnClickListener(onImageClickListener);
        iv_dis_ok.setOnClickListener(onImageClickListener);
        iv_global_add.setOnClickListener(onImageClickListener);
        iv_global_delete.setOnClickListener(onImageClickListener);
        iv_global_ok.setOnClickListener(onImageClickListener);
        
        itemDiscountService = ServiceManager.getInstance().mDiscountSettingService;
        globalDiscountService = ServiceManager.getInstance().mGlobalDiscountSettingService;
        bindItemDiscountData();
        bindGlobalDiscountData();
        
        setPage(0);
        itemDiscountAdapter.ScrollToRow(0);
        ChangeMode.mode = 1;
        btn_exit.setEnabled(true);
	}
	
	private void bindItemDiscountData(){
		listItemDiscount = itemDiscountService.FindAll();
		if (listItemDiscount == null) {
			return;
		}
		if (itemDiscountAdapter == null) {
			itemDiscountAdapter = new ItemDiscountAdapter(this, listItemDiscount);
			itemDiscountAdapter.setEditableListener(mEditableListener);
		}
		lv_itemDiscountlist.setAdapter(itemDiscountAdapter);
	}
	
	private void bindGlobalDiscountData(){
		listGlobalDiscount = globalDiscountService.FindAll();
		if (listGlobalDiscount == null) {
			return;
		}
		if (globalDiscountAdapter == null) {
			globalDiscountAdapter = new GlobalDiscountAdapter(this, listGlobalDiscount);
			globalDiscountAdapter.setEditableListener(mEditableListener);
		}
		lv_globalDiscountList.setAdapter(globalDiscountAdapter);
	}
	
	
	private EditableListener mEditableListener = new EditableListener(){

		public void onEdited(String str) {
			if(str.equals(ItemDiscountAdapter.DISCOUNT_EDITED)){
				SetEnabledFalse(1);
			}else if (str.equals(GlobalDiscountAdapter.GLOBALDISCOUNT_EDITED)) {
				SetEnabledFalse(2);
			}
		}
    };
    
    public void SetEnabledFalse(int mode){
		isModified = true;
		scrollLayout.setEnable(false);
    	switch (mode) {
    	case 1:		//item discount setting
    		lv_itemDiscountlist.setEnabled(false);
    		btn_exit.setEnabled(false);
    		iv_dis_delete.setVisibility(View.INVISIBLE);
    		iv_dis_add.setVisibility(View.INVISIBLE);
    		iv_dis_ok.setVisibility(View.VISIBLE);
    		break;
    	case 2:		//global discount setting
    		lv_globalDiscountList.setEnabled(false);
    		btn_exit.setEnabled(false);
    		iv_global_delete.setVisibility(View.INVISIBLE);
    		iv_global_add.setVisibility(View.INVISIBLE);
    		iv_global_ok.setVisibility(View.VISIBLE);
    		break;
    	}
    }
    
    public OnClickListener onImageClickListener = new OnClickListener() {

		public void onClick(View v) {
			String ls_desc,ls_value,ls_type,flag;
			int dis_no,global_no;
			int msg = -1;
			switch (v.getId()) {
			case R.id.iv_dis_add:
				isModified = true;
				scrollLayout.setEnable(false);
				ItemDiscountSetting ds = new ItemDiscountSetting();
				if (listItemDiscount == null) {
					dis_no = 1;
				}else if (listItemDiscount.size() == 0) {
					dis_no = 1;
				}else {
//					dis_no = listItemDiscount.size() + 1;
					dis_no = itemDiscountService.getMaxDisNo() + 1;
				}
				ds.setFlag("I");
				ds.setDs_type("P");
				ds.setDs_no(dis_no);
				ds.setDs_desc("");
				ds.setDs_follow_item(true);
				listItemDiscount.add(ds);
				itemDiscountAdapter.setSource(listItemDiscount);
				itemDiscountAdapter.notifyDataSetChanged();
				itemDiscountAdapter.ScrollToRow(listItemDiscount.size() - 1);
				lv_itemDiscountlist.setSelection(lv_itemDiscountlist.getAdapter().getCount() - 1);
				lv_itemDiscountlist.setEnabled(false);
				
				iv_dis_add.setVisibility(View.INVISIBLE);
				iv_dis_delete.setVisibility(View.INVISIBLE);
				iv_dis_ok.setVisibility(View.VISIBLE);
				btn_exit.setEnabled(false);
				break;
			case R.id.iv_dis_ok:
				ItemDiscountSetting ds1 = new ItemDiscountSetting();
				for (int i = listItemDiscount.size() - 1; i >= 0; i--) {
					boolean editNow = false;
					ls_desc = listItemDiscount.get(i).getDs_desc().trim();
					dis_no = listItemDiscount.get(i).getDs_no();
					ls_type = listItemDiscount.get(i).getDs_type();
					ls_value = String.valueOf(listItemDiscount.get(i).getDs_value());
					flag = listItemDiscount.get(i).getFlag();
					editNow = listItemDiscount.get(i).isEdit();
					if (ls_desc == null || ls_desc.equals("") || 
							ls_value == null || ls_value.equals("")) {
						listItemDiscount.remove(i);
						result = true;
					}else if (Double.valueOf(ls_value) <= 0) {
						ShowMessage("The Value can not be empty",
								mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);
						return;
					}else {
						if (editNow) {
							ls_value = String.format("%.2f",Double.valueOf(ls_value));
							ds1.setDs_no(dis_no);
							ds1.setDs_desc(ls_desc);
							ds1.setDs_value(Double.valueOf(ls_value));
							ds1.setDs_type(ls_type);
							ds1.setDs_follow_item(listItemDiscount.get(i).isDs_follow_item());
							ds1.setDs_tax1(listItemDiscount.get(i).isDs_tax1());
							ds1.setDs_tax2(listItemDiscount.get(i).isDs_tax2());
							ds1.setDs_tax3(listItemDiscount.get(i).isDs_tax3());
							ds1.setDs_tax4(listItemDiscount.get(i).isDs_tax4());
							ds1.setDs_tax5(listItemDiscount.get(i).isDs_tax5());
							ds1.setDs_tax6(listItemDiscount.get(i).isDs_tax6());
							ds1.setDs_foodstamp(listItemDiscount.get(i).isDs_foodstamp());
							
							ds1.setCreate_datetime(MoleQUtil.getDateToString("yyyyMMddHHmmss", now));
							ds1.setUpdate_datetime(MoleQUtil.getDateToString("yyyyMMddHHmmss", now));
							if (flag == "I") {
								result = itemDiscountService.insertItemDiscountSetting(ds1);
								if (GlobalInfo.getInstance().isMGNetwork) {
									mMGCreateFiles.createrFile(ds1.toMGData("INSERT"));
								}
							}else {
								result = itemDiscountService.updateItemDiscountSetting(ds1);
								if (GlobalInfo.getInstance().isMGNetwork) {
									mMGCreateFiles.createrFile(ds1.toMGData("UPDATE"));
								}
							}
						}
					}
				}
				if (result) {
					ShowMessage(result);
					listItemDiscount = itemDiscountService.FindAll();
					itemDiscountAdapter.setSource(listItemDiscount);
					itemDiscountAdapter.notifyDataSetChanged();
					Keyboard();
					lv_itemDiscountlist.setEnabled(true);
					btn_exit.setEnabled(true);
					itemDiscountAdapter.ScrollToRow(0);
					lv_itemDiscountlist.setSelection(0);
					iv_dis_ok.setVisibility(View.INVISIBLE);
					iv_dis_delete.setVisibility(View.VISIBLE);
					iv_dis_add.setVisibility(View.VISIBLE);
					isModified = false;
					scrollLayout.setEnable(true);
				}
				break;
			case R.id.iv_dis_delete:
				if(listItemDiscount.size() == 0) return;
				int index = itemDiscountAdapter.GetSelectedIndex();
				dis_no = listItemDiscount.get(index).getDs_no();
				if (itemDiscountService.PriceSettingHaveItemDiscount(dis_no)) {
					ShowMessage(
							"This discount entry cannot be removed because it is linked to price setting.",
							mMessageDialog.MESSAGE_BOX_OK,
							mMessageDialog.ICON_INFO);
					return;
				}else if (itemDiscountService.MMSettingHaveItemDiscount(dis_no)) {
					ShowMessage(
							"This discount entry cannot be removed because it is linked to mm setting.",
							mMessageDialog.MESSAGE_BOX_OK,
							mMessageDialog.ICON_INFO);
					return;
				}else if (itemDiscountService.FuncPanelHaveItemDiscount(dis_no)) {
					ShowMessage(
							"This discount entry cannot be removed because it is linked to function panel.",
							mMessageDialog.MESSAGE_BOX_OK,
							mMessageDialog.ICON_INFO);
					return;
				}
				msgType = 1;
				ShowMessage("Do you want to delete this item discount setting?",
						mMessageDialog.MESSAGE_BOX_YES_NO,mMessageDialog.ICON_INFO);
				break;
			case R.id.iv_global_add:
				isModified = true;
				scrollLayout.setEnable(false);
				GlobalDiscountSetting gd = new GlobalDiscountSetting();
				if (listGlobalDiscount == null) {
					global_no = 1;
				}else if (listGlobalDiscount.size() == 0) {
					global_no = 1;
				}else {
//					global_no = listGlobalDiscount.size() + 1;
					global_no = globalDiscountService.getMaxGlobalNo() + 1;
				}
				gd.setType("I");
				gd.setGd_no(global_no);
				gd.setGd_desc("");
				listGlobalDiscount.add(gd);
//				globalDiscountAdapter.setSource(listGlobalDiscount);
//				globalDiscountAdapter.notifyDataSetChanged();
				globalDiscountAdapter.ScrollToRow(listGlobalDiscount.size() - 1);
				lv_globalDiscountList.setSelection(lv_globalDiscountList.getAdapter().getCount() - 1);
				lv_globalDiscountList.setEnabled(false);
				
				iv_global_add.setVisibility(View.INVISIBLE);
				iv_global_delete.setVisibility(View.INVISIBLE);
				iv_global_ok.setVisibility(View.VISIBLE);
				btn_exit.setEnabled(false);
				break;
			case R.id.iv_global_ok:
				GlobalDiscountSetting gd1 = new GlobalDiscountSetting();
				for (int i = listGlobalDiscount.size() - 1; i >= 0; i--) {
					boolean editNow = false;
					ls_desc = listGlobalDiscount.get(i).getGd_desc().trim();
					global_no = listGlobalDiscount.get(i).getGd_no();
					ls_type = listGlobalDiscount.get(i).getType();
					ls_value = String.valueOf(listGlobalDiscount.get(i).getGd_value());
					editNow = listGlobalDiscount.get(i).isEdit();
					if (ls_desc == null || ls_desc.equals("") || 
							ls_value == null || ls_value.equals("")) {
						listGlobalDiscount.remove(i);
						result = true;
					}else if (Double.valueOf(ls_value) <= 0) {
						ShowMessage("The Value can not be empty",
								mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);
						return;
					}else {
						if (editNow) {
							ls_value = String.format("%.2f",Double.valueOf(ls_value));
							gd1.setGd_no(global_no);
							gd1.setGd_desc(ls_desc);
							gd1.setGd_value(Double.valueOf(ls_value));
							gd1.setType("G");
							gd1.setCreate_datetime(MoleQUtil.getDateToString("yyyyMMddHHmmss", now));
							gd1.setUpdate_datetime(MoleQUtil.getDateToString("yyyyMMddHHmmss", now));
							
							if (ls_type == "I") {
								result = globalDiscountService.insertGlobalDiscountSetting(gd1);
								if (GlobalInfo.getInstance().isMGNetwork) {
									mMGCreateFiles.createrFile(gd1.toMGData("INSERT"));
								}
							}else {
								result = globalDiscountService.updateGlobalDiscountSetting(gd1);
								if (GlobalInfo.getInstance().isMGNetwork) {
									mMGCreateFiles.createrFile(gd1.toMGData("UPDATE"));
								}
							}
						}
					}
				}
				if (result) {
					ShowMessage(result);
					listGlobalDiscount = globalDiscountService.FindAll();
					globalDiscountAdapter.setSource(listGlobalDiscount);
					globalDiscountAdapter.notifyDataSetChanged();
					Keyboard();
					lv_globalDiscountList.setEnabled(true);
					btn_exit.setEnabled(true);
					globalDiscountAdapter.ScrollToRow(0);
					lv_globalDiscountList.setSelection(0);
					iv_global_ok.setVisibility(View.INVISIBLE);
					iv_global_delete.setVisibility(View.VISIBLE);
					iv_global_add.setVisibility(View.VISIBLE);
					isModified = false;
					scrollLayout.setEnable(true);
				}
				break;
			case R.id.iv_global_delete:
				if(listGlobalDiscount.size() == 0) return;
				int index2 = globalDiscountAdapter.GetSelectedIndex();
				global_no = listGlobalDiscount.get(index2).getGd_no();
				if (globalDiscountService.FuncPanelHaveGlobalDiscount(global_no)) {
					ShowMessage(
							"This discount entry cannot be removed because it is linked to function panel.",
							mMessageDialog.MESSAGE_BOX_OK,
							mMessageDialog.ICON_INFO);
					return;
				}
				msgType = 2;
				ShowMessage("Do you want to delete this global discount setting?",
						mMessageDialog.MESSAGE_BOX_YES_NO,mMessageDialog.ICON_INFO);
				break;
			}
		}
    	
    };
    
    public void setPage(int page){
		switch (page) {
		case 0:
			iv_1_w1.setVisibility(View.VISIBLE);
			iv_1_b2.setVisibility(View.VISIBLE);
			
			iv_2_b1.setVisibility(View.INVISIBLE);
			iv_2_w2.setVisibility(View.INVISIBLE);
			break;
		case 1:
			iv_1_w1.setVisibility(View.INVISIBLE);
			iv_1_b2.setVisibility(View.VISIBLE);
			
			iv_2_b1.setVisibility(View.VISIBLE);
			iv_2_w2.setVisibility(View.VISIBLE);
			break;
		}
    }
	
    public OnClickListener onPageClickListener = new OnClickListener() {
		
		public void onClick(View v) {
			Keyboard();
			switch (v.getId()) {
			case R.id.iv_1_b2:
				scrollLayout.snapToScreen(1);
				break;
			case R.id.iv_2_b1:
				scrollLayout.snapToScreen(0);
				break;
			}
		}
	};
    
	public OnClickListener onClickListener = new OnClickListener() {

		public void onClick(View view) {
			switch (view.getId()) {
			case R.id.ll_left:
				Keyboard();
				break;
			case R.id.ll_right:
				Keyboard();
				break;
			case R.id.btn_exit:
				msgType = 0;
				ShowMessage(getResources().getString(R.string.msg_exit_program),
						MessageDialog.MESSAGE_BOX_YES_NO,
						MessageDialog.ICON_INFO);
				break;
			}
		}
	};
	
	public void UpdateMessage(int msg){
		switch (msg) {
		case 1:
			Toast.makeText(DiscountSettingActivity.this, "Save Completed.", Toast.LENGTH_SHORT).show();
			break;
		case 0:
			break;
		case -1:
			ShowMessage("Save Error.",
					mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);
			break;
		}
	}
	
	public void ShowMessage(boolean re){
		if (re) {
			Toast.makeText(DiscountSettingActivity.this, "Save Completed.", Toast.LENGTH_SHORT).show();
		}else {
			ShowMessage("Save Error.",
					mMessageDialog.MESSAGE_BOX_OK,mMessageDialog.ICON_INFO);

		}
	}
	
	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		String type,flag;
		int dis_no,global_no;
		public void onClickYes() {
			switch (msgType) {
			case 0:
				finish();
				break;
			case 1:
				int index1 = itemDiscountAdapter.GetSelectedIndex();
				dis_no = listItemDiscount.get(index1).getDs_no();
				type = listItemDiscount.get(index1).getDs_type();
				flag = listItemDiscount.get(index1).getFlag();
				if (flag.equals("I")) {
					listItemDiscount.remove(index1);
					result = true;
				}else {
					result = itemDiscountService.deleteItemDiscountSetting(dis_no);
					if (GlobalInfo.getInstance().isMGNetwork) {
						mMGCreateFiles.createrFile(listItemDiscount.get(index1).toMGData("DELETE"));
					}
//					result = itemDiscountService.updateSetItemDiscountNo(dis_no);
//					if (GlobalInfo.getInstance().isMGNetwork) {
//						for (int i = index1 + 1; i < listItemDiscount.size(); i++) {
//							mMGCreateFiles.createrFile(listItemDiscount.get(i).toMGData("UPDATE"));
//						}
//					}
				}
				if (result) {
					listItemDiscount = itemDiscountService.FindAll();
					itemDiscountAdapter.setSource(listItemDiscount);
					itemDiscountAdapter.notifyDataSetChanged();
					mMessageDialog.dismiss();
					if (index1 != 0) {
						itemDiscountAdapter.ScrollToRow(index1 - 1);
					}else {
						itemDiscountAdapter.ScrollToRow(0);
					}
				}
				break;
			case 2:
				int index2 = globalDiscountAdapter.GetSelectedIndex();
				global_no = listGlobalDiscount.get(index2).getGd_no();
				type = listGlobalDiscount.get(index2).getType();
				if (type.equals("I")) {
					listItemDiscount.remove(index2);
					result = true;
				}else {
					result = globalDiscountService.deleteGlobalDiscountSetting(global_no);
					if (GlobalInfo.getInstance().isMGNetwork) {
						mMGCreateFiles.createrFile(listGlobalDiscount.get(index2).toMGData("DELETE"));
					}
//					result = globalDiscountService.updateSetGlobalDiscountNo(global_no);
//					if (GlobalInfo.getInstance().isMGNetwork) {
//						for (int i = index2 + 1; i < listGlobalDiscount.size(); i++) {
//							mMGCreateFiles.createrFile(listGlobalDiscount.get(i).toMGData("UPDATE"));
//						}
//					}
				}
				if (result) {
					listGlobalDiscount = globalDiscountService.FindAll();
					globalDiscountAdapter.setSource(listGlobalDiscount);
					globalDiscountAdapter.notifyDataSetChanged();
					mMessageDialog.dismiss();
					if (index2 != 0) {
						globalDiscountAdapter.ScrollToRow(index2 - 1);
					}else {
						globalDiscountAdapter.ScrollToRow(0);
					}
				}
				break;
			}
		}
		
		public void onClickNo() {
			mMessageDialog.dismiss();
		}

		public void onClickOK() {
			mMessageDialog.dismiss();
		}
	};
	
	public void ShowMessage(String text, int type, int icon) {
		mMessageDialog = new MessageDialog(DiscountSettingActivity.this);
		mMessageDialog.setStyle(type);
		mMessageDialog.setMessageIcon(icon);
		mMessageDialog.setMessage(text);
		mMessageDialog.setOnClickMessageListener(onClickMessageListener);
		mMessageDialog.show();
	}
	
	public void Keyboard(){
		try {
			InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputMethodManager.hideSoftInputFromWindow(DiscountSettingActivity.this
					.getCurrentFocus().getWindowToken(), 
					InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) {
			return;
		}
	}
}
